//
//  DynamicDualRowView.swift
//  LYOnlineBanking
//
//  Created by 李永彬 on 2025/7/29.
//

import UIKit
import SnapKit
import SDWebImage

class DynamicDualRowView: UIView {
    
    struct Item {
        let turboentItem: TurboentItem?
        let normalImage: UIImage?
        let complateImage: UIImage?
        let action: (() -> Void)?
    }
    
    var currentAction: (() -> Void)? = nil
    // 布局参数
    private let rowSpacing: CGFloat = 20
    private let itemSpacing: CGFloat = 15
    private let maxItemsPerRow = 2
    private let maxItemWidth: CGFloat = 180 // 最大宽度限制
    private let minItemWidth: CGFloat = 120 // 最小宽度限制
    
    // 数据源
    private var items: [Item] = []
    
    private lazy var centerImageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFit
        iv.clipsToBounds = false
        iv.image = UIImage(named: "product_center")
        return iv
    }()
    
    // 主垂直栈
    private lazy var verticalStack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.distribution = .fill
        stack.alignment = .center
        stack.spacing = rowSpacing
        stack.isUserInteractionEnabled = true
        return stack
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        backgroundColor = .clear
        addSubview(verticalStack)
        addSubview(centerImageView)
        
        verticalStack.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        centerImageView.snp.makeConstraints { make in
            make.center.equalTo(verticalStack)
            make.width.height.equalTo(135)
        }
    }
    
    func configure(with items: [Item]) {
        self.items = items
        verticalStack.arrangedSubviews.forEach { $0.removeFromSuperview() }
        
        // 分割数据到行
        let firstRowItems = Array(items.prefix(maxItemsPerRow))
        let secondRowItems = Array(items.suffix(from: min(maxItemsPerRow, items.count)))
        
        // 创建行
        createRow(items: firstRowItems, row: 1)
        if !secondRowItems.isEmpty {
            createRow(items: secondRowItems, row: 2)
        }
    }
    
    private func createRow(items: [Item], row: Int) {
        let rowStack = UIStackView()
        rowStack.axis = .horizontal
        rowStack.distribution = .fill
        rowStack.alignment = .center
        rowStack.spacing = itemSpacing
        rowStack.isUserInteractionEnabled = true
        // 计算行内所有item的总宽度
        var totalItemsWidth: CGFloat = 0
        var itemSizes: [CGSize] = []
        
        for item in items {
            let size = calculateItemSize(for: item.normalImage)
            itemSizes.append(size)
            totalItemsWidth += size.width
        }
        
        // 添加item之间的间距
        totalItemsWidth += CGFloat(items.count - 1) * itemSpacing
        
        // 单item时居中处理
        if items.count == 1 {
            let container = UIView()
            let button = createButton(item: items[0], size: itemSizes[0])
            container.addSubview(button)
            
            if row == 1 {
                button.updateBottomItemViewLayout(.topLeft)
            }else if row == 2 {
                button.updateBottomItemViewLayout(.bottomRight)
            }
            
            button.snp.makeConstraints { make in
                make.top.bottom.equalToSuperview()
                make.leading.trailing.equalToSuperview().offset(40)
                make.size.equalTo(itemSizes[0])
            }
 
            rowStack.addArrangedSubview(container)
        } else {
            for (index, item) in items.enumerated() {
                let button = createButton(item: item, size: itemSizes[index])
                
                if row == 1 {
                    if index % 2 == 0 {
                        button.updateTopItemViewLayout(.topLeft)
                    } else {
                        button.updateTopItemViewLayout(.topRight)
                    }
                   
                } else {
                    if index % 2 == 0 {
                        button.updateBottomItemViewLayout(.bottomLeft)
                    } else {
                        button.updateBottomItemViewLayout(.bottomRight)
                    }
                }
                
                rowStack.addArrangedSubview(button)
                
                button.snp.makeConstraints { make in
                    make.size.equalTo(itemSizes[index])
                }
            }
        }
        
        verticalStack.addArrangedSubview(rowStack)
        
        // 限制行宽度不超过父视图宽度
        rowStack.snp.makeConstraints { make in
            make.width.lessThanOrEqualToSuperview()
        }
    }
    
    private func calculateItemSize(for image: UIImage?) -> CGSize {
        guard let image = image else {
            return CGSize(width: minItemWidth, height: minItemWidth)
        }
        
        // 计算保持图片宽高比的合适尺寸
        let imageRatio = image.size.width / image.size.height
        var itemWidth = min(maxItemWidth, image.size.width)
        itemWidth = max(minItemWidth, itemWidth)
        let itemHeight = itemWidth / imageRatio
        
        return CGSize(width: itemWidth, height: itemHeight)
    }
    
    private func createButton(item: Item, size: CGSize) -> ActionButton {
        let button = ActionButton()
        
        button.setModel(item)
        
        var bgImage = item.normalImage
        if let cardiarium = item.turboentItem?.cardiarium,
           cardiarium == 1 {
            bgImage = item.complateImage
        }

        if let image = bgImage{
            button.setBackgroundImage(image, for: .normal)
            button.imageView?.contentMode = .scaleAspectFit
            button.backgroundColor = .clear
        }
        
        if let action = item.action {
            button.tapAction = action
            button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
        }
        
        button.layer.cornerRadius = 8
        button.clipsToBounds = true
        
        return button
    }
    
    @objc func buttonTapped(_ sender: ActionButton) {

        sender.tapAction?()
    }
}

// 使用自定义Button类
class ActionButton: UIButton {
    var tapAction: (() -> Void)?
    
    enum ItemPosition {
        case topRight
        case topLeft
        case bottomRight
        case bottomLeft
    }
    
    private lazy var contentLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 14)
        label.textColor = UIColor(hex: "#FFFFFF")
        label.textAlignment = .left
        label.text = "Identity authentication"
        label.numberOfLines = 0
        return label
    }()
    
    private lazy var stateLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 10, weight: .medium)
        label.textColor = UIColor(hex: "#000000")
        label.textAlignment = .center
        label.text = LYlocalizedString("Certification completed")
        label.backgroundColor = UIColor(hex: "#14F900")
        label.layer.masksToBounds = true
        label.layer.cornerRadius = 12
        return label
    }()
    
    private lazy var iconImgView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFit
        iv.backgroundColor = .clear
        iv.image = UIImage(named: "tou_xiang")
        return iv
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        commonInitSubviews()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func commonInitSubviews() {
        addSubview(contentLabel)
        addSubview(stateLabel)
        addSubview(iconImgView)
        setTopItemViewLayout()
    }
    
    func setTopItemViewLayout() {
        
        contentLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().inset(40)
            make.trailing.equalToSuperview().inset(25)
            make.top.equalToSuperview().offset(10)
        }
        
        stateLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().inset(30)
            make.trailing.equalToSuperview().inset(15)
            make.centerY.equalToSuperview()
            make.height.equalTo(24)
        }
        
        iconImgView.snp.makeConstraints { make in
            make.centerX.equalToSuperview().offset(-20)
            make.bottom.equalToSuperview().offset(-10)
            make.width.equalTo(40)
            make.height.equalTo(30)
        }
    }
    
    func setItem(position: ItemPosition) {
        switch position {
        case .topRight, .topLeft:
            updateTopItemViewLayout(position)
        case .bottomRight, .bottomLeft:
            updateBottomItemViewLayout(position)
        }
    }
    
    func updateTopItemViewLayout(_ position: ItemPosition) {
        
        contentLabel.snp.remakeConstraints { make in
            make.leading.equalToSuperview().inset(40)
            make.trailing.equalToSuperview().inset(25)
            make.top.equalToSuperview().offset(10)
        }
        
        var stateOffset = 30
        if position == .topRight {
            stateOffset = 10
        }
        
        var stateTOffset = -15
        if position == .topRight {
            stateTOffset = -30
        }
        stateLabel.snp.remakeConstraints { make in
            make.leading.equalToSuperview().inset(stateOffset)
            make.trailing.equalToSuperview().offset(stateTOffset)
            make.centerY.equalToSuperview()
            make.height.equalTo(24)
        }
        
        var offset = -15
        if position == .topRight {
            offset = 15
        }
        iconImgView.snp.remakeConstraints { make in
            make.centerX.equalToSuperview().offset(offset)
            make.bottom.equalToSuperview().offset(-10)
            make.width.equalTo(40)
            make.height.equalTo(30)
        }
    }
    
    func updateBottomItemViewLayout(_ position: ItemPosition) {
        
        var offset = -20
        if position == .bottomRight {
            offset = 20
        }
        iconImgView.snp.remakeConstraints { make in
            make.centerX.equalToSuperview().offset(offset)
            make.top.equalToSuperview().offset(40)
            make.width.equalTo(40)
            make.height.equalTo(30)
        }
        
        contentLabel.snp.remakeConstraints { make in
            make.leading.equalToSuperview().inset(40)
            make.trailing.equalToSuperview().inset(25)
            make.bottom.equalToSuperview().offset(-10)
        }
        
        var stateOffset = 30
        if position == .bottomRight {
            stateOffset = 10
        }
        
        var stateTOffset = -15
        if position == .bottomRight {
            stateTOffset = -30
        }
        stateLabel.snp.remakeConstraints { make in
            make.leading.equalToSuperview().inset(stateOffset)
            make.trailing.equalToSuperview().offset(stateTOffset)
            make.centerY.equalToSuperview().offset(15)
            make.height.equalTo(24)
        }
    }
    
    func setModel(_ item: DynamicDualRowView.Item) {
        contentLabel.text = item.turboentItem?.cipitfication
        if let cardiarium = item.turboentItem?.cardiarium,
           cardiarium == 1 {
            stateLabel.text = LYlocalizedString("Certification completed")
            stateLabel.backgroundColor = UIColor(hex: "#14F900")
            stateLabel.textColor = UIColor(hex: "#000000")
        } else {
            stateLabel.text = LYlocalizedString("Go authenticate")
            stateLabel.backgroundColor = UIColor(hex: "#1E4FF3")
            stateLabel.textColor = UIColor(hex: "#FFFFFF")
        }
        
        let queryString = NetworkManager.shared.commonParameters.toURLQueryString()
        if let baseURL = item.turboentItem?.onyman,
           let urlString = "\(baseURL)?\(queryString)".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
            iconImgView.sd_setImage(with: URL(string: urlString),
                                    placeholderImage: nil,
                                    options: .retryFailed,
                                    context: nil)
        }
    }
}

